﻿using GetSlaughterItem.API.Application.Commands.Week01.Manageres;
using MediatR;
using SlaughterItem.Common.Domains.Setup;
using SlaughterItem.Common.Dtos;
using SlaughterItem.Common.Infrastructures.Interfaces;
using SlaughterItem.Enum;

namespace GetSlaughterItem.API.Application.Commands.Week02.SetupCommand
{
    /// <summary>
    /// 扣减项显示
    /// </summary>
    public class DeductionsQueryHandler : IRequestHandler<DeductionsQueryCommand, Result>
    {
        /// <summary>
        /// 扣减项仓储
        /// </summary>
        private readonly IBaseRepositoryGet<Deductions> deductionsRepository;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="deductionsRepository">扣减项仓储</param>
        public DeductionsQueryHandler(IBaseRepositoryGet<Deductions> deductionsRepository)
        {
            this.deductionsRepository = deductionsRepository;
        }

        /// <summary>
        /// 业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(DeductionsQueryCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Success };

            try
            {
                var list = deductionsRepository.GetAll().Where(x=>x.IsDel==0).ToList();
                if (!string.IsNullOrEmpty(request.DeductionName))
                {
                    list = list.Where(x => x.DeductionName.Contains(request.DeductionName)).ToList();
                }

                if (request.DeductionStatu==null)
                {
                    list=list.Where(x=>x.DeductionStatu==request.DeductionStatu).ToList();
                }
                var totalCount = list.Count;
                var totalPage = (int)Math.Ceiling(totalCount * 1.0 / request.PageSize);

                list = list.OrderBy(x => x.DeductionId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();


                var DeductionData = new
                {
                    totalCount,
                    totalPage,
                    list
                };
                result.Data = DeductionData;
            }
            catch (Exception)
            {

                throw;
            }

            return result;
         }
    }
}
